<template>
	<div class="p-6 space-y-6">

		<el-row :gutter="20">
			<el-col :span="8">
				<el-card>
					<el-statistic title="总订单数" :value="totalOrders" />
				</el-card>
			</el-col>
			<el-col :span="8">
				<el-card>
					<el-statistic title="总销售额 (元)" :value="totalSales" precision="2" />
				</el-card>
			</el-col>
			<el-col :span="8">
				<el-card>
					<el-statistic title="热门商品" :value="topProduct" />
				</el-card>
			</el-col>
		</el-row>

		<el-card>
			<h3 class="text-lg font-semibold mb-4">📈 近 30 天销售趋势</h3>
			<div id="sales-chart" style="height: 300px;"></div>
		</el-card>

		<el-card>
			<h3 class="text-lg font-semibold mb-4">🏷️ 热门商品排行</h3>
			<el-table :data="rankedProducts" border>
				<el-table-column type="index" label="#" width="50" />
				<el-table-column prop="name" label="商品名" />
				<el-table-column prop="quantity" label="销量" />
			</el-table>
		</el-card>
	</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'

const orders = ref([])
const totalOrders = ref(0)
const totalSales = ref(0)
const topProduct = ref('')
const rankedProducts = ref([])

onMounted(() => {
	orders.value = JSON.parse(localStorage.getItem('orders') || '[]')

	totalOrders.value = orders.value.length
	totalSales.value = orders.value.reduce((sum, o) => sum + parseFloat(o.total), 0).toFixed(2)

	const productMap = {}
	orders.value.forEach(o => {
		productMap[o.name] = (productMap[o.name] || 0) + o.quantity
	})
	const sorted = Object.entries(productMap).sort((a, b) => b[1] - a[1])
	rankedProducts.value = sorted.slice(0, 5).map(([name, quantity]) => ({ name, quantity }))
	topProduct.value = sorted[0]?.[0] || '-'

	const chart = echarts.init(document.getElementById('sales-chart'))
	const days = Array.from({ length: 30 }).map((_, i) => {
		const d = new Date()
		d.setDate(d.getDate() - (29 - i))
		return d.toLocaleDateString()
	})
	const dailySales = days.map(day => {
		const sum = orders.value
			.filter(o => o.time.includes(day))
			.reduce((acc, o) => acc + parseFloat(o.total), 0)
		return sum.toFixed(2)
	})
	chart.setOption({
		tooltip: { trigger: 'axis' },
		xAxis: { type: 'category', data: days },
		yAxis: { type: 'value' },
		series: [{ name: '销售额', type: 'line', data: dailySales }]
	})
})
</script>

<style scoped>
.text-xl {
	font-size: 1.25rem;
}
</style>
  
